package cn.csc.module.member.service.role;

import cn.csc.framework.common.pojo.PageResult;
import cn.csc.module.member.controller.app.role.vo.AppMemberRoleCreateReqVO;
import cn.csc.module.member.controller.app.role.vo.AppMemberRoleExportReqVO;
import cn.csc.module.member.controller.app.role.vo.AppMemberRolePageReqVO;
import cn.csc.module.member.controller.app.role.vo.AppMemberRoleUpdateReqVO;
import cn.csc.module.member.convert.role.MemberRoleConvert;
import cn.csc.module.member.dal.dataobject.role.MemberRoleDO;
import cn.csc.module.member.dal.mysql.role.MemberRoleMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.math.BigInteger;
import java.util.Collection;
import java.util.List;

import static cn.csc.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.csc.module.member.enums.ErrorCodeConstants.ROLE_NOT_EXISTS;

/**
 * 会员角色 Service 实现类
 *
 * @author liuchuang
 */
@Service
@Validated
public class MemberRoleServiceImpl extends ServiceImpl<MemberRoleMapper, MemberRoleDO> implements MemberRoleService {


    @Override
    public BigInteger createRole(AppMemberRoleCreateReqVO createReqVO) {
        // 插入
        MemberRoleDO role = MemberRoleConvert.INSTANCE.convert(createReqVO);
        baseMapper.insert(role);
        // 返回
        return role.getId();
    }

    @Override
    public void updateRole(AppMemberRoleUpdateReqVO updateReqVO) {
        // 校验存在
        validateRoleExists(updateReqVO.getId());
        // 更新
        MemberRoleDO updateObj = MemberRoleConvert.INSTANCE.convert(updateReqVO);
        baseMapper.updateById(updateObj);
    }

    @Override
    public void deleteRole(BigInteger id) {
        // 校验存在
        validateRoleExists(id);
        // 删除
        baseMapper.deleteById(id);
    }

    private void validateRoleExists(BigInteger id) {
        if (baseMapper.selectById(id) == null) {
            throw exception(ROLE_NOT_EXISTS);
        }
    }

    @Override
    public MemberRoleDO getRole(BigInteger id) {
        return baseMapper.selectById(id);
    }

    @Override
    public List<MemberRoleDO> getByUserId(BigInteger userId){
        return baseMapper.selectByUserId(userId);
    }

    @Override
    public List<MemberRoleDO> getRoleList(Collection<BigInteger> ids) {
        return baseMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<MemberRoleDO> getRolePage(AppMemberRolePageReqVO pageReqVO) {
        return baseMapper.selectPage(pageReqVO);
    }

    @Override
    public List<MemberRoleDO> getRoleList(AppMemberRoleExportReqVO exportReqVO) {
        return baseMapper.selectList(exportReqVO);
    }

}
